<template>
  <div class="timestamp-converter">
    <h1 class="title">时间戳转换</h1>
    
    <div class="current-time-section">
      <div class="time-display">
        <p>当前时间（北京时间）: {{ currentTime }}</p>
        <p>当前时间戳: {{ currentTimestamp }}</p>
      </div>
    </div>

    <div class="conversion-section">
      <div class="conversion-row">
        <h2>时间转化为时间戳</h2>
        <div class="input-group">
          <input 
            v-model="timeInput" 
            type="text" 
            class="time-input"
            placeholder="请输入时间，格式如：2023-01-01 12:00:00"
          />
          <button @click="convertToTimestamp" class="convert-button">转换</button>
        </div>
        <div class="result" v-if="timestampResult !== null">
          <p>转换后的时间戳(毫秒): {{ timestampResult }}</p>
        </div>
      </div>

      <div class="conversion-row">
        <h2>时间戳转化为时间</h2>
        <div class="input-group">
          <input 
            v-model="timestampInput" 
            type="number" 
            class="timestamp-input"
            placeholder="请输入时间戳"
          />
          <button @click="convertToTime" class="convert-button">转换</button>
        </div>
        <div class="result" v-if="timeResult">
          <p>转换后的时间 (YYYY-MM-DD HH:mm:ss): {{ timeResult.hyphenFormat }}</p>
          <p>转换后的时间 (YYYY/MM/DD HH:mm:ss): {{ timeResult.slashFormat }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'

// 当前时间相关
const currentTime = ref('')
const currentTimestamp = ref(0)
let timer: number | null = null

// 时间转时间戳相关
const timeInput = ref('')
const timestampResult = ref<number | null>(null)

// 时间戳转时间相关
const timestampInput = ref('')
const timeResult = ref<{
  hyphenFormat: string,
  slashFormat: string
} | null>(null)

// 更新当前时间（仅更新显示时间，不更新时间戳）
const updateCurrentTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', { 
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
  // 注意：这里不更新时间戳，只更新时间显示
}

// 时间转换为时间戳
const convertToTimestamp = () => {
  if (!timeInput.value) {
    alert('请输入时间')
    return
  }
  
  // 支持多种时间格式
  const date = new Date(timeInput.value)
  if (isNaN(date.getTime())) {
    alert('请输入有效的时间格式，例如：2023-01-01 12:00:00')
    return
  }
  
  timestampResult.value = date.getTime()
}

// 时间戳转换为时间
const convertToTime = () => {
  if (!timestampInput.value) {
    alert('请输入时间戳')
    return
  }
  
  const timestamp = parseInt(timestampInput.value)
  if (isNaN(timestamp)) {
    alert('请输入有效的时间戳')
    return
  }
  
  const date = new Date(timestamp)
  
  // 获取年月日时分秒
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  // 两种格式：- 分割和 / 分割
  const hyphenFormat = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  const slashFormat = `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
  
  timeResult.value = {
    hyphenFormat,
    slashFormat
  }
}

// 组件挂载时启动定时器并设置初始时间戳
onMounted(() => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', { 
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
  // 只在初始化时设置时间戳
  currentTimestamp.value = Math.floor(now.getTime())
  
  // 只更新时间显示，不更新时间戳
  timer = window.setInterval(updateCurrentTime, 1000)
})

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.timestamp-converter {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.current-time-section {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  text-align: center;
}

.time-display p {
  margin: 10px 0;
  font-size: 18px;
  color: #555;
}

.conversion-section {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.conversion-row {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.conversion-row h2 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.input-group {
  display: flex;
  gap: 10px;
  align-items: center;
  margin: 15px 0;
  flex-wrap: wrap;
}

.time-input,
.timestamp-input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  flex: 1;
  min-width: 200px;
}

.convert-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.convert-button:hover {
  background-color: #0056b3;
}

.result {
  margin-top: 15px;
  padding: 10px;
  background-color: #e9f7ef;
  border-radius: 4px;
  border-left: 4px solid #28a745;
}

.result p {
  margin: 5px 0;
  font-size: 16px;
  color: #155724;
}

@media (max-width: 600px) {
  .input-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .time-input,
  .timestamp-input,
  .convert-button {
    width: 100%;
  }
}
</style>